<template>
	<div class="col-md-8">
		<carousel v-if="showCarousel"></carousel>
		<item :list="items"></item>
		<loading :show="!ready" :end="pageEnd"></loading>
	</div>
</template>
<script>
	import Carousel from 'packages/carousel/carousel'
	import Item from 'particals/item/item'
	import Loading from 'packages/loading/loading'
	import {getScrollTop,getClientHeight,getScrollHeight,scrollTo} from 'common/dom'
    import {mapGetters, mapMutations} from 'vuex'
    import {setTitle} from 'common/dom'

	export default {
		computed: {
			showCarousel() {
				return this.website.carousel
			},
            ...mapGetters([
              'website'
            ])
        },
		data() {
			return {
				scrollWatch: true,
				page: 1,
				page_size: 5,
				total: 0,
				ready: true,
				pageEnd: false,
				items: []
			}
		},
		created() {
            setTitle(this.$title.home)
			scrollTo(0);
			this.__getList();
			window.addEventListener('scroll', this.handleScroll);
		},
		methods: {
			handleScroll() {
				if(!this.scrollWatch || this.pageEnd) {
					return false;
				}
				if(getScrollHeight() - (getScrollTop() + getClientHeight()) <= 80) {
					if(!this.checkReady()){
						return false;
					}
					this.__getList();
				}
			},
			checkReady() {
				if(this.ready) {
					if(this.page === this.total){
						this.pageEnd = true;
						return false;
					}
					this.page++;
					return true;
				}else{
					return false;
				}
			},
			__getList() {
				if(!this.ready) {
					return false;
				}
				this.ready = false;
				this.$http.get('/topics',{params: this.__buildParams()}).then((resource)=>{
					if(this.page == 1) {
						this.setDataReady(true);
					}
					let total = resource.data.meta.total_nums;
					this.total = Math.ceil(total / this.page_size);
					if(this.items.length){
						for (var i = 0; i <= resource.data.data.length - 1; i++) {
							this.items.push(resource.data.data[i]);
						}
					}else{
						this.items = resource.data.data;
					}
					if(total === this.items.length) {
						this.pageEnd = true;
					}
					let _this=this;
					setTimeout(()=>{
						_this.ready = true;
					},50);
				});
			},
			__buildParams() {
				return {
					page: this.page,
					page_size: this.page_size
				}
			},
            ...mapMutations({
              setDataReady: 'SET_DATA_READY'
            })
		},
		destroyed (){
			this.scrollWatch = false;
		},
		components: {
			Carousel,Item,Loading
		}
	}	
</script>